<?php
defined('IN_PHPCMS') or exit('No permission resources.');
pc_base::load_app_class('admin', 'admin', 0);
pc_base::load_sys_class('format', '', 0);
pc_base::load_sys_class('form', '', 0);
/**
 * 少儿报名管理
 */
class manage extends admin {
	private $db;
	public $siteid;
	function __construct() {
		parent::__construct();
		$this->db = pc_base::load_model('reg_child_model');//加载报名主题model
		$this->log = pc_base::load_model('reg_child_log_model');//加载报名记录model
		$this->source = pc_base::load_model('reg_child_source_model');//加载报名记录model 
		$this->vote_db = pc_base::load_model('vote_subject_model');//加载投票model
		$this->vote_option_db = pc_base::load_model('vote_option_model');//加载投票选项model
		$this->course_db = pc_base::load_model('course_nsr_model');//加载课程model
		$this->talent = pc_base::load_model('talent_model');//加载人才model
		$this->contest_db = pc_base::load_model('contest_model');//加载课程model
		$this->order_detail_db = pc_base::load_model('order_detail_model');//加载课程model
		$this->siteid = $this->get_siteid();// 获取当前站点ID
		$this->admin_userid = param::get_cookie('userid');//获取当前登录的管理员ID
		if(!$this->siteid) $this->siteid = 1;
		//报名类型
		$this->reg_type = array('1'=>'赛事','2'=>'培训');
		//获取投票
		$where = array('status'=>1,'siteid'=>$this->siteid);
		$vote = array();
		$vote_info = $this->vote_db->select($where,'id,subject');
		foreach ($vote_info as $k=>$v){
			$vote[$v['id']] = $v['subject'];
		}
		$this->vote = $vote;
		//获取课程
		$condition = array('status'=>1,'siteid'=>$this->siteid);
		$course = array();
		$course_info = $this->course_db->select($condition,'id,name');
		foreach ($course_info as $k=>$v){
			$course[$v['id']] = $v['name'];
		}
		$this->course = $course;
		//获取赛事
		$condition1 = array('status'=>1,'siteid'=>$this->siteid,'is_activity'=>0);
		$contest = array();
		$contest_info = $this->contest_db->select($condition1,'id,name');
		foreach ($contest_info as $k=>$v){
			$contest[$v['id']] = $v['name'];
		}
		$this->contest = $contest;
	}
	
	/**
	 * 报名列表
	 */
	public function init() {
	    $where = ' siteid='.$this->siteid.' and status = 1 ';
        //搜索框
        $title = empty($_GET['title']) ?'':trim($_GET['title']);#报名标题
        if(!empty($title)){
            $where .= ' and title like "%'.$title.'%"';
        }
        //获取管理员真实姓名数据
        $admin_model = pc_base::load_model('admin_model');
        $adminInfo = $admin_model->getRealnameInfo();
		$page = $_GET['page']?intval($_GET['page']):1;
		$reg_info = $this->db->listinfo($where,'id DESC',$page,10);
		foreach ($reg_info as $k=>$v){
			$reg_info[$k]['reg_num'] = $this->log->count(array('reg_child_model_id'=>$v['id']));//统计报名主题的报名数量
		}
		$pages = $this->db->pages;
		$big_menu = array('javascript:window.top.art.dialog({id:\'add\',iframe:\'?m=reg_child&c=manage&a=add\', title:\''.L('add_reg').'\', width:\'780\', height:\'620\', lock:true}, function(){var d = window.top.art.dialog({id:\'add\'}).data.iframe;var form = d.document.getElementById(\'dosubmit\');form.click();return false;}, function(){window.top.art.dialog({id:\'add\'}).close()});void(0);', L('add_reg'));
		include $this->admin_tpl('reg_list');
	}
	
	/**
	 * 添加报名
	 */
	public function add() {
		if(isset($_POST['dosubmit'])) {
			$reg = isset($_POST['reg']) ? $_POST['reg'] : showmessage(L('illegal_parameters'),HTTP_REFERER);
			$reg['created_by'] = $reg['updated_by'] = $this->admin_userid;
			$reg['create_time'] = $reg['update_time'] = date('Y-m-d H:i:s');
			$reg['siteid'] = $this->siteid;
			$reg['status'] = 1;
			if (isset($reg['number'])) {
				$number_id = $this->check_number($reg['number']);
				if (!$number_id) {
					showmessage(L('number_exits'),HTTP_REFERER);
				}
			}
			$result = $this->db->insert($reg,true);
			if ($result) {
				//记录行为日志
				$log_content = '<span style="color:#00CC00;">添加报名</span>[新生成报名id：'.$result.'，标题：'.$reg['title'].']';
                $this->manage_admin_log($log_content);

				showmessage(L('operation_success'),'?m=reg_child&c=manage','','add');
			} else {
				showmessage(L('operation_failure'), HTTP_REFERER);
			}
		} else {
			$show_header = $show_validator = '';
			include $this->admin_tpl('reg_add');
		}
	}

	/**
	 * 修改报名
	 */
	public function edit() {
		if (!isset($_GET['id']) || empty($_GET['id'])) {
            showmessage(L('illegal_action'), HTTP_REFERER);
        }
        $id = intval($_GET['id']);
		if(isset($_POST['dosubmit'])) {
			$reg = isset($_POST['reg']) ? $_POST['reg'] : showmessage(L('illegal_parameters'),HTTP_REFERER);
			$reg['updated_by'] = $this->admin_userid;
			$reg['update_time'] = date('Y-m-d H:i:s');
			if ($reg['reg_type'] == 1) {
				$reg['course_id'] = "";
			} elseif ($reg['reg_type'] == 2) {
				$reg['contest_id'] = "";
			}
			if (isset($reg['number'])) {
				$number_id = $this->check_number($reg['number']);
				if (!$number_id) {
					showmessage(L('number_exits'),HTTP_REFERER);
				}
			}
			$result = $this->db->update($reg,array('id'=>$id));
			if ($result) {
				//记录行为日志
                $log_content = '<span style="color:blue;">修改报名</span>[报名id：'.$id.'，标题：'.$_POST['reg']['title'].']';
                $this->manage_admin_log($log_content);

				showmessage(L('operation_success'),'?m=reg_child&c=manage','','edit');
			} else {
				showmessage(L('operation_failure'), HTTP_REFERER);
			}
		} else {
			$info = $this->db->get_one(array('id'=>$id));
			$show_header = $show_validator = '';
			include $this->admin_tpl('reg_edit');
		}
	}

	/**
	 * 删除报名
	 */
	public function delete() {
		if (!isset($_GET['id']) || empty($_GET['id'])) {
            showmessage(L('illegal_action'), HTTP_REFERER);
        }
        $id = intval($_GET['id']);
        $info = $this->db->get_one(array('id'=>$id));
        $result = $this->db->update(array('status'=>2),array('id'=>$id));

        if ($result) {
        	//记录行为日志
        	$log_content = '<span style="color:red;">删除报名</span>[报名id：'.$id.'，标题：'.$info['title'].']';
        	$this->manage_admin_log($log_content);
            showmessage(L('operation_success'), HTTP_REFERER);
        } else {
            showmessage(L("operation_failure"), HTTP_REFERER);
        }
	}

	/**
	 * 报名统计
	 */
	public function reg_statistics(){
		if ($_GET['child_source'] == 1) {
			//来源报名统计
			if (!isset($_GET['source']) || !isset($_GET['channel']) || !isset($_GET['source_id'])) {
				showmessage(L('illegal_action'), HTTP_REFERER);
			}
			$id = $_GET['source_id'];
			$page = $_GET['page'] ? intval($_GET['page']) : 1;
			$source = $_GET['source'];
			$channel = $_GET['channel'];
			$condition = "";
			$condition .= "source = '".$source."' and channel = '".$channel."'";
			//搜索
			$name = $_GET['name']?trim($_GET['name']):'';
			$tel = $_GET['tel']?trim($_GET['tel']):'';
			if (!empty($name)) {
				$condition .= " and child_name like '%$name%'";
			}
			if (!empty($tel)) {
				$condition .= " and tel = ".$tel;
			}
			$reg_info = $this->source->get_one(array('id'=>$id));
			$info = $this->log->listinfo($condition,'id DESC',$page,10);
			$pages = $this->log->pages;
			$child_source = 1;
			$show_header = false;
		} else {
			//少儿报名统计
			if (!isset($_GET['res_id']) || empty($_GET['res_id'])) {
				showmessage(L('illegal_action'), HTTP_REFERER);
			}
			$reg_id = intval($_GET['res_id']);//报名主题ID
			//搜索
			$where = "";
			$where = "reg_child_model_id = ".$reg_id;
			$name = $_GET['name']?trim($_GET['name']):'';
			$tel = $_GET['tel']?trim($_GET['tel']):'';
			$is_pay = intval($_GET['is_pay']);
			if (!empty($name)) {
				$where .= " and child_name like '%$name%'";
			}
			if (!empty($tel)) {
				$where .= " and tel = ".$tel;
			}
			//是否支付：是
			if($is_pay == 1){
			    $where .= " and is_pay =".$is_pay;
			}
			//是否支付：否
			if($is_pay == 2){
			    $where .= " and is_pay = 0 ";
			}
			$reg_info = $this->db->get_one(array('id'=>$reg_id));
			$page = $_GET['page'] ? intval($_GET['page']) : 1;
			$info = $this->log->listinfo($where,'id DESC',$page,10);
			$pages = $this->log->pages;
			$child_source = 0;
			$show_header = false;
		}
		include $this->admin_tpl('reg_statistics');
	}
	
	/**
	 * 报名统计详情-孩子信息修改
	 */
	public function reg_statistics_edit() {
	    $id = $_GET['id'];
		if (!isset($id) || empty($id)) {
			showmessage(L('illegal_action'), HTTP_REFERER);
		}

		if(isset($_POST['dosubmit'])) {
// 		    echo '<pre>';print_r($_POST);die; 
            $child_name = $_POST['child_name'];
		    
		    //人才ID
		    $talent_id = $_POST['talent_id'];
		    
		    //少儿报名表记录中主键ID
		    $child_log_id = $_POST['child_log_id'];
		    
		    //查询出该报名记录所属的报名主题id : $reg_child_model_id
		    $reg_child_model_id = $this->log->select(' id = '.$child_log_id,'reg_child_model_id');
		    $reg_child_model_id = $reg_child_model_id[0]['reg_child_model_id'];
		    
		    //查询出该报名记录所属的投票主题id : $vote_id
		    $vote_id = $this->db->select(' id = '.$reg_child_model_id,'vote_id');
		    $vote_id = $vote_id[0]['vote_id'];
		    
		    if(!$child_log_id && !$talent_id){
		        showmessage(L('illegal_parameters'),HTTP_REFERER);
		    }
		    //更新 nsrweb_reg_child_model_log 表中 孩子照片字段（child_image）值
		    $reg_log_info['child_image'] = $_POST['child_image'];//child_image:孩子照片
		    $result_reg_log = $this->log->update($reg_log_info,array('id'=>$id));

		    //更新 nsrweb_talent 表中 image_square（人物方形图）
		    if($talent_id){
		        $talent_info['updated_by'] = $this->admin_userid;
		        $talent_info['update_time'] = date('Y-m-d H:i:s');
		        $talent_info['image_square'] = $_POST['child_image'];//image_square:人物方形图
		        $result_talent = $this->talent->update($talent_info,array('id'=>$talent_id));
		    }
		    
		    //更新 nsrweb_vote_option 表中 image字段(投票选项照片)值
		    if($vote_id && $talent_id){
		        $vote_info['image'] = $_POST['child_image'];//image_square:人物方形图
		        $result_vote = $this->vote_option_db->update($vote_info,array('subjectid'=>$vote_id,'source_id'=>$talent_id));
		    }
		    
		    
		    if ($result_reg_log) {
		        //记录行为日志
		        $log_content = '<span style="color:blue;">修改少儿报名孩子照片</span>[孩子姓名：'.$child_name.']';
		        $this->manage_admin_log($log_content);
		        showmessage(L('operation_success'),'?m=reg_child&c=manage','','edit');
		    } else {
		        showmessage(L('operation_failure'), HTTP_REFERER);
		    }
		} else {
    		$id = intval($_GET['id']);
    		$infos = $this->log->get_one(array('id'=>$id));
    		include $this->admin_tpl('reg_statistics_edit');
		}
	}
	
	/**
	 * 报名统计详情
	 */
	public function reg_statistics_detail() {
		if ($_GET['child_source'] == 1) {
			if (!isset($_GET['source']) || !isset($_GET['channel']) || !isset($_GET['id'])) {
				showmessage(L('illegal_action'), HTTP_REFERER);
			}
			$source = $_GET['source'];
			$channel = $_GET['channel'];
			$id = intval($_GET['id']);
			$source_id = intval($_GET['source_id']);//来源ID
			$infos = $this->log->get_one(array('id'=>$id));
			$child_source = 1;
			$show_header = false;
		} else {
			if (!isset($_GET['id']) || empty($_GET['id'])) {
				showmessage(L('illegal_action'), HTTP_REFERER);
			}
			$id = intval($_GET['id']);
			$reg_id = intval($_GET['res_id']);//报名主题ID
			$infos = $this->log->get_one(array('id'=>$id));
			$child_source = 0;
			$show_header = false;
		}
		include $this->admin_tpl('reg_statistics_detail');
	}
	
	/**
	 * 报名订单统计
	 */
	public function order_statistics() {
		if (!isset($_GET['res_id']) || empty($_GET['res_id'])) {
			showmessage(L('illegal_action'), HTTP_REFERER);
		}
		$page = $_GET['page'] ? intval($_GET['page']) : 1;
		$reg_id = intval($_GET['res_id']);//报名主题ID
		$where = "source_id = ".$reg_id;
		//搜索
		if (isset($_GET['search'])) {
			if ($_GET['name']!="") {
				$name = $_GET['name'];
				$where .= " and name like '%$name%'";
			}
			if ($_GET['order_id']!="") {
				$order_id = $_GET['order_id'];
				$where .= " and order_id = ".$order_id;
			}
		}
		$order_info = $this->order_detail_db->listinfo($where,'id DESC',$page,10);
		$pages = $this->order_detail_db->pages;
		$reg_info = $this->db->get_one(array('id'=>$reg_id));
		include $this->admin_tpl('order_statistics');
	}
	
	/**
	 * 检测报名编号前缀，防止重复
	 */
	private function check_number($number){
		if (!isset($number)) {
			showmessage(L('operation_failure'),HTTP_REFERER);
		}
		if ($_GET['id']) {
			$info = $this->db->get_one(array('id'=>$_GET['id'],'siteid'=>$this->siteid,'status'=>1));
			if($info['number'] == $number){
				return true;
			}
		}
		$id = $this->db->get_one(array('number'=>$number,'siteid'=>$this->siteid,'status'=>1),'id');
		if ($id['id']){
			return false;
		} else {
			return true;
		}
	}
	
	/**
	 * 生成二维码
	 */
	public function qrcode() {
		$url = $_GET['url'];
		$show_header = false;
		include $this->admin_tpl('qrcode');
	}
	
	/**
	 * 来源权限设置
	 */
	public function permission_set() {
		$where = '';
		$reg_auth = pc_base::load_model('reg_child_source_auth_model');
		$datas = $reg_auth->listinfo($where,' id desc',$_GET['page'],20);
		$pages = $reg_auth->pages;
		//获取管理员真实姓名数据
		$admin_model = pc_base::load_model('admin_model');
		$adminInfo = $admin_model->getRealnameInfo();
// 		//取赛区
// 		$model_setting=pc_base::load_model('site_setting_model');
// 		$contest_district = $model_setting->getValue("contest_district",$this->siteid);
// 		//取报名类型
// 		$reg_type = $model_setting->getValue("reg_type",$this->siteid);
		//取来源
		$sourceList = $this->source->sourceList($this->siteid);
		$big_menu = array('javascript:window.top.art.dialog({id:\'add\',iframe:\'?m=reg_child&c=manage&a=permission_add\', title:\''.L('add_reg_source_auth').'\', width:\'580\', height:\'220\', lock:true}, function(){var d = window.top.art.dialog({id:\'add\'}).data.iframe;var form = d.document.getElementById(\'dosubmit\');form.click();return false;}, function(){window.top.art.dialog({id:\'add\'}).close()});void(0);', L('add_reg_source_auth'));
		include $this->admin_tpl('reg_auth');
	}
	
	/**
	 * 添加来源权限
	 */
	public function permission_add() {
		$reg_auth = pc_base::load_model('reg_child_source_auth_model');
		if(isset($_POST['dosubmit'])) {
			$data = array();
			//获取管理员真实姓名数据
			$admin_model = pc_base::load_model('admin_model');
			$adminInfo = $admin_model->getRealnameInfo();
			$info = $this->source->get_one(array('id'=>$_POST['source_id']));
			$username = '';
			$userauth = '';
			foreach ($_POST['user_id'] as $k => $v) {
				$authInfo = $reg_auth->get_one(array('source_id'=>$_POST['source_id'],'userid'=>$v));
				if (empty($authInfo)) {
					$data[$k]['source_id'] = $_POST['source_id'];
					$data[$k]['userid'] = $v;
					$data[$k]['siteid'] = $this->siteid;
					$data[$k]['create_time'] =date("Y-m-d H:i:s",time());
					$data[$k]['created_by'] = $_SESSION['userid'];
					$data[$k]['update_time'] =date("Y-m-d H:i:s",time());
					$data[$k]['updated_by'] = $_SESSION['userid'];
					$username .=  $username?','.$adminInfo[$v]:$adminInfo[$v];
				} else {
					$userauth = $username?','.$adminInfo[$v]:$adminInfo[$v];
					$res = $reg_auth->update(array('update_time'=>date('Y-m-d H:i:s',time())),array('id'=>$authInfo['id']));
				}
			}
			if(!empty($data)){
				$res = $reg_auth->multiInsert($data);
			}
			if ($res) {
				//记录行为日志
				$log_content = '<span style="color:#00CC00;">添加来源权限</span>[来源id：'.$_POST['source_id'].'，名称：'.$info['cn_name'].'与管理员的绑定('.$username.')，已绑定的管理员('.$userauth.')]';
				$this->manage_admin_log($log_content);
				
				showmessage(L('operation_success'),'?m=reg_chile&c=manage&a=permission_set','','add');
			} else {
				showmessage(L('operation_failure'), HTTP_REFERER);
			}
		} else {
			//取来源
			$sourceList = $this->source->sourceList($this->siteid);
			//取绑定管理员
			$model_setting=pc_base::load_model('site_setting_model');
			$rolelist = $model_setting->getValue("source_role_user",$this->siteid);
			$role = array();
			foreach ($rolelist as $k => $v) {
				$admin_model = pc_base::load_model('admin_model');
				$admin_role_model = pc_base::load_model('admin_role_model');
				$info = $admin_role_model->get_one(array('roleid'=>$v));
				$role[$v]['user_list'] = $admin_model->select(array('roleid'=>$v));
				$role[$v]['name'] = $info['rolename'];
			}
			pc_base::load_sys_class('form','',0);
			$show_header = $show_validator = '';
			include $this->admin_tpl('power_add');
		}
	}
	
	/**
	 * 删除来源权限
	 */
	public function permission_del() {
		//取来源
		$sourceList = $this->source->sourceList($this->siteid);
		//获取管理员真实姓名数据
		$admin_model = pc_base::load_model('admin_model');
		$adminInfo = $admin_model->getRealnameInfo();
		$reg_auth = pc_base::load_model('reg_child_source_auth_model');
		if (! isset($_REQUEST['id']) || empty($_REQUEST['id'])) {
			showmessage(L('illegal_action'), HTTP_REFERER);
		}
		$id = $_REQUEST['id'];
		$str = '';
		if (is_array($id)) {
			foreach ($id as $k => $v) {
				if (intval($v)) {
					$info = $reg_auth->get_one(array('id'=>$v));
					$str .= ($str?'、':'').'删除来源(id:'.$info['reg_id'].',名称：'.$sourceList[$info['reg_id']].')和管理员(id:'.$info['userid'].',真实姓名:'.$adminInfo[$info['userid']].')权限';
				} else {
					unset($id[$k]);
				}
			}
			$id = implode('\',\'', $id);
		} else {
			$info = $reg_auth->get_one(array('id'=>$id));
			$str .= '删除来源(id:'.$info['reg_id'].',名称：'.$sourceList[$info['reg_id']].')和管理员(id:'.$info['userid'].',真实姓名:'.$adminInfo[$info['userid']].')权限';
		}
		$result = $reg_auth->delete("id in ('$id')");
		
		//记录行为日志
		$log_content = '<span style="color:red;">删除来源权限</span>['.$str.']';
		$this->manage_admin_log($log_content);
		
		if ($result) {
			showmessage(L('operation_success'), HTTP_REFERER);
		} else {
			showmessage(L('operation_failure'), HTTP_REFERER);
		}
	}

}